package com.zhang.server.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhang.server.common.Result;
import com.zhang.server.controller.request.UserPageRequest;
import com.zhang.server.entity.User;
import com.zhang.server.mapper.UserMapper;
import com.zhang.server.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserService implements IUserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public List<User> list() {
        return userMapper.list();
    }

    @Override
    public Object page(UserPageRequest userPageRequest) {
        // 将pageNum、pageSize作为参数传进方法
        PageHelper.startPage(userPageRequest.getPageNum(), userPageRequest.getPageSize());
        List<User> userList = userMapper.listByCondition(userPageRequest);

        System.out.println(userList.get(0));
        // 将查询结果放到这里,返回，就会自动分页
        return new PageInfo<>(userList);
    }

    @Override
    public Integer save(User user) {
        // 用户名当作卡号处理
        user.setUsername(DateUtil.format(new Date(), "yyyyMMdd") + Math.abs(IdUtil.fastSimpleUUID().hashCode()));
        return userMapper.save(user);
    }

    @Override
    public Result getById(Integer id) {
        return Result.success(userMapper.getById(id));
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void delete(Integer id) {
        userMapper.delete(id);
    }

    @Override
    public User getByUsername(String username) {
        return userMapper.getByUsername(username);
    }
}
